package com.niit.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.niit.common.Result;
import com.niit.model.Book;
import com.niit.service.BookService;
import com.niit.service.impl.BookServiceImpl;

/**
 * Servlet implementation class ReadBookServlet
 */
@WebServlet("/ReadBookServlet.do")
public class ReadBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ReadBookServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		Result result = null;
		
		String id = request.getParameter("id");
		if (id == null || "".equals(id)) {
			result = Result.error("参数缺失");
		} else {
			// 根据id读取书籍信息
			BookService bookService = new BookServiceImpl();
			Book book = bookService.getBookById(Integer.valueOf(id));
			if (book != null) {
				result = Result.success("获取书籍成功", book);
			} else {
				result = Result.error("获取书籍信息失败");
			}
			// 返回JSON数据给前端
			JSONObject json = (JSONObject) JSONObject.toJSON(result);
			writer.print(json);
			writer.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
